package com.lulalei.dbviewer.commons.utils;

import com.lulalei.dbviewer.commons.exception.CustomizeException;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * 读取pom.xml文件属性的工具类
 */
public class PomReaderUtils {
    /**
     * 获取root模块的pom.xml的model
     */
    public static Model getRootPomModel() throws IOException, XmlPullParserException {
        String rootPath = System.getProperty("user.dir");
        String myPomPath = rootPath + File.separator + "pom.xml";
        return getPomModel(myPomPath);
    }

    /**
     * 获取当前模块的pom.xml的model
     */
    public static Model getCurrentPomModel() throws IOException, XmlPullParserException {
        String path = PomReaderUtils.class.getResource("/").getPath();
        String myPomPath = new File(path).getParentFile().getParent() + File.separator + "pom.xml";
        return getPomModel(myPomPath);
    }

    /**
     * 获取子模块的pom.xml的model
     */
    public static Model getChildrenPomModel(String childrenName) throws IOException, XmlPullParserException, CustomizeException {
        String rootPath = System.getProperty("user.dir");
        File file = new File(rootPath + File.separator + childrenName);
        if (!file.exists()){
            throw new CustomizeException("不存在该模块");
        }
        String myPomPath = file.getPath() + File.separator + "pom.xml";
        return getPomModel(myPomPath);
    }

    /**
     * 获取模块的组织
     */
    public static String getGroupId() throws XmlPullParserException, IOException {
       return getRootPomModel().getGroupId();
    }

    /**
     * 获取模块的组件id
     */
    public static String getArtifactId(Model model){
        return model.getArtifactId();
    }

    /**
     * 获取子模块
     */
    public static List<String> getModules(Model model){
        return model.getModules();
    }

    /**
     * 获取路径中的pom文件的对象
     */
    private static Model getPomModel(String path) throws IOException, XmlPullParserException {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        return reader.read(new FileReader(path));
    }
}
